package com.zxmc.handler;

import com.alibaba.fastjson.JSON;
import com.zxmc.common.constant.StatusConstant;
import com.zxmc.common.constant.TypeConstant;
import com.zxmc.common.context.BaseContext;
import com.zxmc.common.utils.SpringUtils;
import com.zxmc.pojo.vo.CommunicateVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class ChatWebSocketHandler extends TextWebSocketHandler {

    private Map<String, WebSocketSession> sessions = new HashMap<>();

    private RedisTemplate redisTemplate = SpringUtils.getBean("redisTemplate");//获取redis实例

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String username = session.getUri().getQuery().split("=")[1];
        sessions.put(username, session);


        sendOnline(session, username);
        //更新用户状态
        CommunicateVO build1 = CommunicateVO.builder()
                .userName(username)
                .createTime(LocalDateTime.now())
                .type(TypeConstant.userOn)
                .build();
        String jsonString1 = JSON.toJSONString(build1);
        for (WebSocketSession webSocketSession : sessions.values()) {
            webSocketSession.sendMessage(new TextMessage(jsonString1));
        }
        System.out.println(username+"上线");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String[] parts = message.getPayload().split(":", 3);
        String username = parts[0];
        String toUser = parts[1];
        String text = parts[2];

//        System.out.println(sessions);
//        System.out.println(Arrays.toString(parts));
        WebSocketSession toSession = sessions.get(toUser);
        if(text.equals("$update")){
            CommunicateVO build = CommunicateVO.builder()
                    .type(TypeConstant.update)
                    .build();
            String jsonString1 = JSON.toJSONString(build);
            if(toSession != null){
                toSession.sendMessage(new TextMessage(jsonString1));
            }
            return;
        }else if(text.equals("$friendUpdate")){
            // 将所有用户名转换为以逗号分隔的字符串
            String onlineUsers = String.join(",", sessions.keySet());
            CommunicateVO build = CommunicateVO.builder()
                    .userName(username)
                    .type(TypeConstant.friendUpdate)
                    .content(onlineUsers)
                    .build();
            String jsonString1 = JSON.toJSONString(build);
            session.sendMessage(new TextMessage(jsonString1));

            sendOnline(session, username);
            return;
        }
        CommunicateVO build = CommunicateVO.builder()
                .userName(username)
                .content(text)
                .friendName(toUser)
                .createTime(LocalDateTime.now())
                .status(StatusConstant.UN_READED)
                .type(TypeConstant.communication)
                .build();
        String jsonString = JSON.toJSONString(build);
        System.out.println(build);
        if (toSession != null) {
            //如果在线,直接发送
            build.setStatus(StatusConstant.READED);
            toSession.sendMessage(new TextMessage(jsonString));
        }
        //存储到redis
        String uniqueKey = "chat:"+username+":"+toUser + ":" + UUID.randomUUID();
        redisTemplate.opsForValue().set(uniqueKey, build,30, TimeUnit.DAYS);

    }

    private void sendOnline(WebSocketSession session, String username) throws IOException {
        // 将所有用户名转换为以逗号分隔的字符串
        String onlineUsers = String.join(",", sessions.keySet());
        CommunicateVO build1 = CommunicateVO.builder()
                .userName(username)
                .createTime(LocalDateTime.now())
                .type(TypeConstant.onlineUsers)
                .content(onlineUsers)
                .build();
        String jsonString2 = JSON.toJSONString(build1);
        session.sendMessage(new TextMessage(jsonString2));
        System.out.println(onlineUsers);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String username = session.getUri().getQuery().split("=")[1];
        sessions.remove(username);

        //更新用户状态
        CommunicateVO build = CommunicateVO.builder()
                .userName(username)
                .createTime(LocalDateTime.now())
                .type(TypeConstant.userOff)
                .build();
        String jsonString = JSON.toJSONString(build);
        for (WebSocketSession webSocketSession : sessions.values()) {
//            System.out.println(webSocketSession);
            webSocketSession.sendMessage(new TextMessage(jsonString));
        }
        System.out.println(username + "离线");
    }
}
